package top.revery.account.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.account.dto.LogUserDto;
import top.revery.api.entity.payWallet.BaseLogUser;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/16 14:32
 */
@Service
public class LogUserService {
    @Autowired
    private LogUserDto logUserDto;

    public Page<BaseLogUser> findPage(int pageNum, int pageSize, Map map) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "addTime");
        Specification<BaseLogUser> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize,Sort.by(order));
        return logUserDto.findAll(specification, pageRequest);
    }

    private Specification<BaseLogUser> createSpecification(Map map) {

        return new Specification<BaseLogUser>() {
            @Override
            public Predicate toPredicate(Root<BaseLogUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
                //用户
                if (map.get("userId") != null && !"".equals(map.get("userId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("userId"), map.get("userId")));
                }
                //类型
                if (map.get("type") != null && !"".equals(map.get("type"))) {
                    predicate.getExpressions().add(cb.equal(root.get("type"), map.get("type")));
                }
                //发布日期查询
                if (map.get("startTime") != null && !"".equals(map.get("startTime"))) {
                    predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("addTime").as(String.class), (String) map.get("startTime")));
                }
                if (map.get("endTime") != null && !"".equals(map.get("endTime"))) {
                    predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("addTime").as(String.class), (String) map.get("endTime")));
                }
                return predicate;
            }
        };

    }
}
